package res;

import com.codahale.metrics.annotation.Timed;

import mybatis.TeacherDao;
import mybatis.UserDao;
import mybatis.conf.MybatisConf;

import org.apache.ibatis.session.SqlSession;
import org.hibernate.validator.constraints.NotEmpty;
import orm.Result;
import orm.Teacher;
import orm.Token;
import orm.*;
import util.JWTToken;

import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by langdon on 2017/7/20.
 */
@Path("/api/v1/teachers")
@Produces(MediaType.APPLICATION_JSON)
public class TeacherRes {

    public TeacherRes(){
        SqlSession sqlSession = MybatisConf.getSession();
        TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);
        teachRooms =  teacherDao.getTeachRooms();
        sqlSession.close();
    }

    private List<String> teachRooms = new ArrayList<>();


    /************************************用户登录后需要认证的操作*************************************/
    /**
     * 通过auth获取老师信息
     * @param auth
     * @return
     */
    @GET
    @Path("/{auth}")
    @Timed
    public  Result getTeacher(
            @NotEmpty@PathParam("auth") String auth
    ){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);
            int userId = Integer.parseInt((String )JWTToken.decode(auth).getPayload().get("id"));
            System.out.println(userId);
            Teacher teacher = teacherDao.getTeacherByUId(userId);
            if(teacher==null)
                return new Result(Status.NOT_FOUND ,"Please become teacher first!");
            else return new TeacherResult(Status.SUCCESS ,"Success",teacher);
        }
        finally {
            sqlSession.close();
        }

    }


    /**
     * 用户认证为老师
     * @param auth 用户鉴权所用的token
     * @return 认证的结果
     */
    @POST
    @Path("/{auth}")
    @Timed
    public  Result registerTeacher(
            @PathParam("auth")String auth
    ){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);
            Token token = JWTToken.decode(auth);
            //1.userId
            int userId = Integer.parseInt((String)token.getPayload().get("id"));
            //该用户尚未认证老师
            if(teacherDao.getTeacherByUId(userId)==null){
                //现在注册

                //2.房间号
                String teachRoom = getRoom();
                //防止房间号出现重复
                while (isDuplicate(teachRoom)){
                    teachRoom=getRoom();
                }

                //3.teacher_create_time
                java.util.Date utilDate=new Date();
                java.sql.Date sqlDate=new java.sql.Date(utilDate.getTime());

                Teacher teacher = new Teacher(userId,teachRoom,sqlDate.toString());

                teacherDao.addTeacher(teacher);
                sqlSession.commit();
                return new TeacherResult(Status.SUCCESS,"Success! You are teacher now!",teacher);

            }
            else return new Result(Status.DUPLICATE,"You has been a teacher!");
        }
        finally {
            sqlSession.close();
        }

    }


    /**
     *更新老师的房间号，用于自定义房间号
     * @param auth 用户名
     * @param room  新的房间号
     * @return
     */
    @PUT
    @Timed
    public Result updateRoom(
            @NotEmpty@QueryParam("auth")String auth,
            @NotEmpty@QueryParam("room")String room
    ){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            TeacherDao teacherDao =sqlSession.getMapper(TeacherDao.class);
            int userId = Integer.parseInt((String)JWTToken.decode(auth).getPayload().get("id"));
            Teacher teacher = teacherDao.getTeacherByUId(userId);

            if(!isDuplicate(room)){
                teacher.setTeacher_room(room);
                teacherDao.updateTeachRoom(teacher);
                sqlSession.commit();
                return new TeacherResult(Status.SUCCESS,"Success!",teacher);
            }
            else return new Result(Status.ERROR,"This roon has been used!Please enter another room.");
        }
        finally {
            sqlSession.close();
        }

    }

    /**
     * 随机生成6位整数作为房间号
     * @return 6位整数
     */
    private  String getRoom(){
        int [] array={0,1,2,3,4,5,6,7,8,9};
        int room=0;
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < 6; i++) {
            if(i==0) room = room * 10 + array[random.nextInt(9)+1];
            else room = room * 10 + array[random.nextInt(10)];
        }
        return String.valueOf(room);
    }

    /**
     * 检查给定的房间号是否被占用
     * @param teachRoom 房间号
     * @return 是否被占用
     */
    private boolean isDuplicate(String teachRoom){
        for (int i = 0; i < teachRooms.size(); i++) {
            if(teachRooms.get(i).equals(teachRoom))
                return true;
        }
        return false;
    }


    /**************************************无需认证的资源请求************************************/

    @GET
    @Path("/teacherId/{teacherId}")
    @Timed
    public Result getTeacher(
            @NotEmpty@PathParam("teacherId")int teacherId
    ){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);
            Teacher teacher = teacherDao.getTeacherByTId(teacherId);
            if(teacher==null){
                return new Result(Status.NOT_FOUND,"Wrong teacher id!");
            }else return new TeacherResult(Status.SUCCESS,"Success!",teacher);
        }
       finally {
            sqlSession.close();
        }
    }

}
